package com.hqq.concurrency.balking;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WashingMachine
 * Created by heqianqian on 2017/7/30.
 */
public class WashingMachine {

    private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);

    private WashingMachineState washingMachineState;

    public WashingMachine() {
        this.washingMachineState = WashingMachineState.ENABLED;
    }

    public void wash() {
        synchronized (this) {
            if (washingMachineState == WashingMachineState.WASHING) {
                LOGGER.info("{}: Error:Machine is Running");
                return;
            }
            washingMachineState = WashingMachineState.WASHING;
        }
        LOGGER.info("{} is Washing..", Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        endOfWashing();
    }

    private synchronized void endOfWashing() {
        LOGGER.info("{} Finished Washing", Thread.currentThread().getName());
        washingMachineState = WashingMachineState.ENABLED;
    }

    public WashingMachineState getWashingMachineState() {
        return washingMachineState;
    }
}
